package com.lujieni.test.testidle;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

public class HelloServer {

    public static void main(String[] args) {
        // 创建启动器类
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                ch.pipeline().addLast(new StringDecoder());
                                ch.pipeline().addLast(new IdleStateHandler(5, 0, 0));
                                ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                                    // only exists in inbound handler
                                    @Override
                                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                                        IdleStateEvent is = (IdleStateEvent) evt;
                                        if (is.state() == IdleState.READER_IDLE) {
                                            System.out.println("读空闲");
                                            ctx.channel().close();
                                        }
                                        super.userEventTriggered(ctx, evt);
                                    }

                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        String content = (String) msg;
                                        System.out.println(content);
                                    }

                                    @Override
                                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                        System.out.println("异常断开,cause:"+cause.getMessage());
                                        super.exceptionCaught(ctx, cause);
                                    }
                                });
                            }
                }).bind(8081);



    }
}
